<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">小区</label>
        <el-select v-model="query.xqId" style="width: 185px;" placeholder="请选择小区" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in xqOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="装修类型" prop="fitmentType">
            <el-select v-model="form.fitmentType" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.house_decoration_type"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="销售类型" prop="saleType">
            <el-radio-group v-model="form.saleType" style="width: 178px">
              <el-radio label="1">出租</el-radio>
              <el-radio label="2">出售</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="户型" prop="houseType">
            <el-select v-model="form.houseType" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.house_type"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="面积" prop="area">
            <el-input v-model="form.area" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="价格" prop="unitPrice">
            <el-input v-model="form.unitPrice" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="朝向">
            <el-input v-model="form.towards" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="楼层" prop="floor">
            <el-input v-model="form.floor" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="有无电梯" prop="lift">
            <el-radio-group v-model="form.lift" style="width: 178px">
              <el-radio label="1">有电梯</el-radio>
              <el-radio label="2">无电梯</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="户型形状">
            <el-input v-model="form.type" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="form.contact" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender" style="width: 178px">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="房屋特点 " prop="label">
            <el-select v-model="form.labels" multiple filterable placeholder="请选择">
              <el-option
                v-for="item in dict.housing_characteristics"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="房屋图片" prop="path">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="10"
              :action="fileUploadApi"
              :headers="headers"
              :on-remove="removePic"
              :on-preview="handlePreview"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :file-list="fileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="1"
              :action="fileUploadApi"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="removeAvatarPic"
              :before-upload="beforeUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleError"
              :file-list="avatarFileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="community" label="小区" />
        <el-table-column prop="fitmentType" label="装修类型">
          <template slot-scope="scope">
            {{ dict.label.house_decoration_type[scope.row.fitmentType] }}
          </template>
        </el-table-column>
        <el-table-column prop="saleType" label="销售类型" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.saleType == 1">出租</span>
            <span v-else-if="scope.row.saleType == 2">出售</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="houseType" label="户型">
          <template slot-scope="scope">
            {{ dict.label.house_type[scope.row.houseType] }}
          </template>
        </el-table-column>
        <el-table-column prop="area" label="面积" >
          <template #default="scope">
            {{ scope.row.area }}平米
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="价格" />
        <el-table-column prop="towards" label="朝向" />
        <el-table-column prop="floor" label="楼层" />
        <el-table-column prop="lift" label="有无电梯" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.lift == 1">有电梯</span>
            <span v-else-if="scope.row.lift == 2">无电梯</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="type" label="户型形状" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="gender" label="性别">
          <template slot-scope="scope">
            <span v-if="scope.row.gender == 1">男</span>
            <span v-if="scope.row.gender == 2">女</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" show-overflow-tooltip />
        <el-table-column prop="labels" label="房屋特点 ">
          <template slot-scope="scope">
            <el-tag
              v-for="tag in scope.row.labels"
              :key="tag"
              :disable-transitions="false"
            >
              {{ dict.label.housing_characteristics[tag] }}
            </el-tag>

          </template>
        </el-table-column>
        <el-table-column prop="shelves" label="房屋状态" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.shelves === 1" style="color: red">未上架</span>
            <span v-else-if="scope.row.shelves === 2" style="color: green">上架</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column v-if="checkPer(['admin','houseManage:edit','houseManage:del'])" label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-button v-if="!scope.row.shelves || scope.row.shelves == 1" size="mini" type="primary" @click="conversionShelves(scope.row.id, 2)">上架</el-button>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-button v-if="scope.row.shelves === 2" size="mini" type="primary" @click="conversionShelves(scope.row.id, 1)">下架</el-button>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple-light">
                  <udOperation
                    :data="scope.row"
                    :permission="permission"
                  />
                </div>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogPictrueVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudHouseManage from '@/api/system/houseManage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { allList } from '@/api/system/regionManage'

const defaultForm = { id: null, createTime: null, updateTime: null, saleType: null, createBy: null, updateBy: null, deleted: null, xqId: null, community: null, fitmentType: null, houseType: null, area: null, unitPrice: '', towards: null, floor: null, lift: null, gender: null, type: null, contact: null, phone: null, label: null, labels: null, shelves: null, avatar: null }
export default {
  name: 'HouseManage',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['house_decoration_type', 'house_type', 'housing_characteristics'],
  cruds() {
    return CRUD({ title: '买卖房屋', url: 'api/houseManage', idField: 'id', sort: 'id,desc', crudMethod: { ...crudHouseManage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'houseManage:add'],
        edit: ['admin', 'houseManage:edit'],
        del: ['admin', 'houseManage:del']
      },
      rules: {
        fitmentType: [
          { required: true, message: '装修类型不能为空', trigger: 'blur' }
        ],
        houseType: [
          { required: true, message: '户型不能为空', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '面积不能为空', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ],
        floor: [
          { required: true, message: '楼层不能为空', trigger: 'blur' }
        ],
        lift: [
          { required: true, message: '请选择有无电梯', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择有无电梯', trigger: 'blur' }
        ],
        saleType: [
          { required: true, message: '请选择有销售类型', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],
        labels: [
          { required: true, message: '标签 不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'community', display_name: '小区' }
      ],
      headers: { 'Authorization': getToken() },
      fileList: [],
      housePhotos: [],
      avatarFileList: [], // 头像图片
      loading: false,
      dialogImageUrl: '',
      dialogPictrueVisible: false,
      xqOptions: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    allList().then(data => {
      if (data && data.data) {
        for (const item of data.data) {
          this.xqOptions.push({ 'value': item.id, 'label': item.communityName })
        }
      }
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.optShow.download = false
      return true
    },
    // 编辑之前
    [CRUD.HOOK.beforeToEdit](obj, row) {
      this.loading = true
      this.avatarFileList.push({ url: row.avatar })
      crudHouseManage.detail(row.id).then(data => {
        if (data && data.details) {
          const housePhoto = data.details
          const resPhotos = []
          for (const item of housePhoto) {
            resPhotos.push({ 'storageId': item.storageId, 'path': item.path })
            this.fileList.push({ response: { id: item.storageId }, url: item.path })
          }
          this.housePhotos = resPhotos
        }
        this.loading = false
      })
      return true
    },
    // 取消添加之前
    [CRUD.HOOK.beforeAddCancel]() {
      this.fileList = []
      this.housePhotos = []
      this.avatarFileList = []
      this.crud.form.avatar = ''
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeEditCancel]() {
      this.fileList = []
      this.housePhotos = []
      this.avatarFileList = []
      this.crud.form.avatar = ''
      return true
    },
    // 提交之前
    [CRUD.HOOK.beforeSubmit]() {
      if (!this.housePhotos || this.housePhotos.length === 0) {
        this.$message.error('请上传文件')
        return false
      }
      if (!this.crud.form.avatar || this.crud.form.avatar === '') {
        this.$message.error('请上传文件')
        return false
      }
      this.crud.form.details = this.housePhotos
      return true
    },
    // 提交保存之后
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.housePhotos = []
      this.avatarFileList = []
      this.crud.form.avatar = ''
      return true
    },
    // 上下架
    conversionShelves(id, shelves) {
      this.loading = true
      crudHouseManage.shelves(id, shelves).then(data => {
        this.loading = false
        this.crud.operationSuccessNotify()
        this.crud.refresh()
      })
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogPictrueVisible = true
    },
    // 删除图片
    removePic(file) {
      const beforRemove = this.housePhotos
      const afterRemove = []
      for (var i = 0; i < beforRemove.length; i++) {
        if (beforRemove[i].storageId !== file.response.id) {
          afterRemove.push(beforRemove[i])
        }
      }
      this.housePhotos = afterRemove
    },
    // 删除头像图片
    removeAvatarPic(file) {
      this.crud.form.avatar = ''
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 5mb!')
      }
      return isLt2M
    },
    handleSuccess(res) {
      this.housePhotos.push({ 'storageId': res.id, 'path': res.path })
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    handleAvatarSuccess(res) {
      this.crud.form.avatar = res.path
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>

